package com.hamster.crmpre.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hamster.crmpre.exception.ExceptionEnum;
import com.hamster.crmpre.exception.LyException;
import com.hamster.crmpre.mapper.CustomerMapper;
import com.hamster.crmpre.mapper.EmployeeMapper;
import com.hamster.crmpre.mapper.PhoneUserMapper;
import com.hamster.crmpre.mapper.ProjectMapper;
import com.hamster.crmpre.pojo.*;
import com.hamster.crmpre.service.EmployeeService;
import com.hamster.crmpre.service.PhoneUserService;
import com.hamster.crmpre.util.JsonUtils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hamster.crmpre.util.aliMessageSend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 手机用户 的Service
 * @author Tarry
 * @create 2019/12/25 10:48
 */
@Service
public class PhoneUserServiceImpl implements PhoneUserService {
    @Autowired
    private PhoneUserMapper phoneUserMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ProjectMapper projectMapper;


    //查询数据库，看用户是否存在
    public PhoneUser getUserByOpenId(String openid){
        return phoneUserMapper.getUserByOpenId(openid);
    }

    //新增用户openId
    @Transactional
    public PhoneUser insertUser(PhoneUser user) {
        phoneUserMapper.insert(user);
        return phoneUserMapper.getUserByOpenId(user.getOpenid());
    }

    /**
     * 分别查询员工表和客户表，判断当前用户是什么角色
     * @param phone
     * @return
     */
    @Override
    public Role queryUser(String phone) {
        Role role = new Role();
//        String projectId = phoneUserMapper.queryCustomer(phone);//查客户表
//        String name = phoneUserMapper.queryCustomerName(phone);//查客户表
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Customer customer = customerMapper.selectOne(queryWrapper);//查询客户对象
        if (customer != null){
            String projectId = customer.getProjectId();
            String name = customer.getName();
            //String departmentName = phoneUserMapper.queryNameByDepartment(customer.getDepartment());//根据部门id查询部门名称

            role.setRole("客户");
            role.setUserId(customer.getId());//客户id
            role.setName(name);//姓名
            //role.setDepartment(departmentName);//部门名称
            List<String> projectList = JsonUtils.parseList(projectId, String.class);
            Set<String> permissionList = new HashSet<>();
            //查询项目id ，属于哪个大分类
            for (String id : projectList) {
                String categoryId = projectMapper.selectById(id).getCategoryId();
                permissionList.add(categoryId);
            }
            String permission = JsonUtils.serialize(permissionList);

            role.setProject(permission);   //客户购买的项目
          //  role.setPermission(permission);//客户购买的项目


            return role;  //返回客户身份
        }

        DepartmentAndPosition departmentAndPosition = phoneUserMapper.queryEmployee(phone);//查员工表
        if (departmentAndPosition != null){
            role.setRole("员工");
            List<String> stringList = new ArrayList<>();
            stringList.add(departmentAndPosition.getDepartment());
            stringList.add(departmentAndPosition.getPosition());
            String permission = JsonUtils.serialize(stringList);
           // role.setPermission(permission); //设置 部门 和 职位

            role.setUserId(departmentAndPosition.getId());
            role.setDepartment(departmentAndPosition.getDepartment()+","+departmentAndPosition.getPosition());//设置 部门
           // role.setPosition(departmentAndPosition.getPosition()); // 设置 职位
            role.setName(departmentAndPosition.getName());  //设置姓名

            return role;
        }
        role.setRole("角色身份异常");
        return role;
    }

    /**
     *  绑定微信手机号
     * @param openId
     * @param phone
     * @return
     */
    @Override
    public PhoneUser setPhone(String openId, String phone) {
        phoneUserMapper.setPhone(openId,phone);
        QueryWrapper<PhoneUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openId);
        PhoneUser phoneUser = phoneUserMapper.selectOne(queryWrapper);
        return phoneUser;
    }

    /**
     * 发送验证码并存入redis
     * @param phone
     */
    @Override
    public void sendPhoneCode(String phone){
     try {
         String msgCode = getMsgCode();
         SendSmsResponse sendSmsResponse = aliMessageSend.sendSms(phone, msgCode);
         if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
             //请求成功,存入redis
             System.out.println("=====success====");
             System.out.println(msgCode);
             //把验证码放入Redis中，并设置有效期为5min
             redisTemplate.opsForValue().set(phone, msgCode, 5, TimeUnit.MINUTES);
         } else {
             System.out.println("=====fail=======");
         }
     }catch (Exception e){
         throw new LyException(ExceptionEnum.PHONE_CODE_FAIL);
     }



    }

    /**
     * 校验手机号，是否已经被他人绑定
     * @param phone
     * @return
     */
    @Override
    public boolean checkPhone(String phone) {
        Integer integer = phoneUserMapper.checkPhone(phone);
        return integer > 0 ? true:false;
    }

    /**
     * 根据是手机号查询该用户的 姓名
     * @param phone
     * @return
     */
    @Override
    public String queryNameByPhone(String phone) {
        QueryWrapper<Customer> customerQueryWrapper = new QueryWrapper<>();
        customerQueryWrapper.eq("phone",phone);
        Customer customer = customerMapper.selectOne(customerQueryWrapper);
        if (customer != null){
            return customer.getName();
        }

        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
        employeeQueryWrapper.eq("phone",phone);
        Employee employee = employeeMapper.selectOne(employeeQueryWrapper);
        if (employee != null){
            return employee.getName();
        }

        return "该用户没有绑定手机号 或 系统没有该用户手机号";
    }

    /**
     * 生成随机的6位数，短信验证码
     * @return
     */
    private static String getMsgCode() {
        int n = 6;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }

}
